<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="Docker Registry Face">
    <meta name="author" content="XiaoBao">

    <title>Docker Registry Face</title>

    <!-- Bootstrap core CSS -->
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap theme -->
    <link href="static/css/bootstrap-theme.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="static/css/theme.css" rel="stylesheet">
</head>

<body>
    <!-- Modal -->
    <div class="modal fade" id="mdl_info" tabindex="-1" role="dialog" aria-labelledby="infoModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title"><span id="sp_info_title"></span></h4>
                </div>
            <div class="modal-body" id="sp_info_body" style="margin-bottom: 10px">
            </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="mdl_show_history" tabindex="-1" role="dialog" aria-labelledby="infoModal">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">标签历史</h4>
                <small><span id="sp_tag_title"></span></small>
                </div>
                <div class="modal-body" style="margin-bottom: 15px">
                    <div class="panel-group" id="div_tag_history_body" role="tablist" aria-multiselectable="true">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="mdl_show_detail" tabindex="-1" role="dialog" aria-labelledby="infoModal">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">标签清单</h4>
                <strong><span id="sp_tag_size"></span></strong><br />
                <small><span id="sp_tag_url"></span></small><br />
                <small><span id="sp_tag_digest"></span></small><br />
                </div>
                <div class="modal-body" style="margin-bottom: 15px">
                    <ul class="list-group" id="ul_tag_detail_body">
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Fixed navbar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false"
                    aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">Docker Registry Face</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="/image_list">镜像列表</a></li>
                    <li><a href="/settings">系统配置</a></li>
                </ul>
            </div>
            <!--/.nav-collapse -->
        </div>
    </nav>

    <div class="container" role="main">
       <div class="row panel panel-default">
            <div class="panel-heading"><a href="/image_list">镜像列表</a> <span id="image_title"></span></div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-9" style="margin-bottom: 13px">
                        <button type="button" class="btn btn-default" id="btn_select_all" onclick="select_all()" disabled>全选</button>
                        <button type="button" class="btn btn-danger" id="btn_del_images" onclick="del_images()" disabled>删除</button>
                        <button type="button" class="btn btn-primary" id="btn_tag_manifest" onclick="get_tag_manifest()" disabled>详情</button>
                        <button type="button" class="btn btn-primary" id="btn_tag_history" onclick="get_tag_history()" disabled>历史</button>
                    </div>

                    <div class="col-md-3" style="margin-bottom: 13px">
                        <div class="input-icon-group">
                            <div class="input-group">
                                <input type="text" class="form-control" id="ipt_search_tags" placeholder="搜索标签 ..." autofocus disabled/>
                                <span class="input-group-addon">
                                    <i class="glyphicon glyphicon-search"> </i>
                                </span> 
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div id="tag_list" class="col-md-12"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- /container -->
    <footer class="footer navbar-fixed-bottom navbar-inverse">
        <div class="container">
            <p class="navbar-text">XiaoBao @2017.3</p>
        </div>
    </footer>
    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="static/js/jquery-3.2.0.min.js"></script>
    <script>
        window.jQuery || document.write('<script src="static/js/jquery-3.2.0.min.js"><\/script>')
    </script>
    <script src="static/js/bootstrap.min.js"></script>
    <script src="static/js/bootstrap-treeview.min.js"></script>
    <script>
        var image = "{{ image }}"
        var source_data = {}

        fetch('/api/v1/tag?image=' + image, {
            method: 'get',
            headers: {"Content-type": "application/json charset=UTF-8"}
        })
        .then(
            function(response) {
                response.json().then(function(data) {
                if (response.status == 200) {
                    var tree_view = []
                    console.log(data.tag_list)
                    $.each(data.tag_list, function(index, value, array) {
                        source_data[value.tag] = value
                        var tag_size = 0
                        $.each(value.layer_detail, function(i, v, a) {
                            tag_size += v.size
                        })
                        tree_view.push({
                            "text":value.tag,
                            "tags":[value.layer_count + " Layers",(tag_size / 1024 / 1024).toFixed(2) + " MB"]
                        })
                    });
                    if (tree_view.length) {
                        $('#tag_list').treeview({
                            data: tree_view,
                            multiSelect: true,
                            levels: 1,
                            showTags: true
                        });
                        $('#btn_select_all').attr('disabled',false)
                        $('#btn_del_images').attr('disabled',false)
                        $('#btn_tag_manifest').attr('disabled',false)
                        $('#btn_tag_history').attr('disabled',false)
                        $('#ipt_search_tags').attr('disabled',false)
                    } else {
                        $('#tag_list').treeview({data: [{"text":"镜像木有标签 ..."}]})
                        $('#tag_list').treeview('disableAll', { silent: true });
                        $('#btn_collapse_all').attr('disabled',true)
                        $('#btn_delete_images').attr('disabled',true)
                        $('#ipt_search_tags').attr('disabled',true)
                    }
                }
            });
        })
        .catch(function(err) {
            alert("标签列表获取异常！" + err);
        });
        
        $('#image_title').text(" > " + image)

        $('#mdl_show_detail').on('hide.bs.modal', function (e) {
            $('#ul_tag_detail_body').empty()
            $('#sp_tag_url').empty()
            $('#sp_tag_size').empty()
            $('#sp_tag_digest').empty()
        })

        $('#mdl_show_history').on('hide.bs.modal', function (e) {
            $('#div_tag_history_body').empty()
        })

        $('#mdl_info').on('hide.bs.modal', function (e) {
            $('#sp_info_title').empty()
            $('#sp_info_body').empty()
            top.location = 'tags?image=' + image
        })

        function get_tag_manifest() {
            var sel_tag = $('#tag_list').treeview('getSelected', { silent: true });
            if (sel_tag.length == 1) {
                var tag_size = 0
                var tag_detail = source_data[sel_tag[0].text]

                $.each(tag_detail.layer_detail, function(index, value, array) {
                    tag_size += value.size
                    $('#ul_tag_detail_body').append("<li class=\"list-group-item\" style=\"word-wrap:break-word\"> \
                        <span class=\"badge\">" + (value.size / 1024 / 1024).toFixed(2) + " MB</span> \
                        <small><strong>mediaType: </strong>"
                        + value.mediaType + "<br/><strong>digest: </strong>"
                        + value.digest + "</small></li>")
                })
                $('#sp_tag_digest').text(tag_detail.digest.split(':')[1])
                $('#sp_tag_url').text(tag_detail.url)
                $('#sp_tag_size').text((tag_size / 1024 / 1024).toFixed(2) + " MB")
                $('#mdl_show_detail').modal('show')
            } else {
                $('#sp_info_title').text('错误')
                $('#sp_info_body').append('<span>没有选择标签或者选择了 <strong>多个标签</strong></span>')
                $('#mdl_info').modal('show')
            }
        }

        function get_tag_history() {
            var sel_tag = $('#tag_list').treeview('getSelected', { silent: true });
            if (sel_tag.length == 1) {
                    fetch('/api/v1/tag/history?image=' + image + '&tag=' + sel_tag[0].text, {
                        method: 'get',
                        headers: {"Content-type": "application/json charset=UTF-8"}
                    })
                    .then(
                        function(response) {
                            response.json().then(function(data) {
                            if (response.status == 200) {
                                $('#sp_tag_title').text(data.image + ":" + data.tag)
                                console.log(data)
                                var history = ""
                                $.each(data.history, function(index, value, array) {
                                    if (value['Cmd']){
                                        history = "<div class=\"panel panel-default\"><div class=\"panel-heading\" role=\"tab\" id=\"head" + value.id + "\">" 
                                        + "<a data-toggle=\"collapse\" data-parent=\"#div_tag_history_body\" href=\"#" + value.id + "\" aria-expanded=\"true\" aria-controls=\""
                                        + value.id + "\">" + value.created.split('T')[0] + " " + value.created.split('T')[1].split('.')[0] + "</a></div>"
                                        + "<div id=\"" + value.id + "\" class=\"panel-collapse collapse\" role=\"tabpanel\" aria-labelledby=\"head" + value.id + "\">"
                                        + "<div class=\"panel-body\" style=\"word-wrap:break-word\"><small>"
                                        + JSON.stringify(value['Cmd']['container_config'])
                                        + "</small></div></div></div>"
                                        $('#div_tag_history_body').append(history)
                                    }
                                })
                            }
                        });
                    })
                    .catch(function(err) {
                        alert("标签列表获取异常！" + err);
                    });
                $('#mdl_show_history').modal('show')
            } else {
                $('#sp_info_title').text('错误')
                $('#sp_info_body').append('<span>没有选择标签或者选择了 <strong>多个标签</strong></span>')
                $('#mdl_info').modal('show')
            }
        }

        function select_all() {
            var node_ids = []
            var all_tags = $('#tag_list').treeview('getSiblings', { silent: true });
            var sel_tags = $('#tag_list').treeview('getSelected', { silent: true });
            $.each(all_tags, function(index, value, array) {
                node_ids.push(value.nodeId)
            })
            if (!sel_tags.length){
                $('#tag_list').treeview('selectNode', [ node_ids, { silent: true } ]);
            } else {
                $('#tag_list').treeview('unselectNode', [ node_ids, { silent: true } ]);
            }
        }

        var search = function(e) {
            var options = {
                ignorecase: true,
                exactmatch: false,
                revealresults: true
            }
            var pattern = $('#ipt_search_tags').val();
            var results = $('#tag_list').treeview('search', [ pattern, options ]);
        }
        $('#ipt_search_tags').on('keyup', search);

        function del_images() {
            var sel_tags = $('#tag_list').treeview('getSelected', { silent: true });
            if (sel_tags.length) {
                $('#sp_info_title').text('删除镜像')
                $('#mdl_info').modal('show')
                $.each(sel_tags, function(index, value, array) {
                    //$('#sp_info_body').empty()

                    $('#sp_info_body').append('<small><span>正在删除镜像 <strong>'
                        + image + ':' + value.text + '</strong> 。第 ' + (index + 1) + ' 个，共 '
                        + sel_tags.length + ' 个。</span><span id=\'sp_tmp_' + index + '\'></span></small><br />'
                    )
                    var body = {
                        "image":image,
                        "tag":value.text
                    }
                    fetch('/api/v1/tag', {
                        body: JSON.stringify(body),
                        method: 'delete',
                        headers: {"Content-type": "application/json charset=UTF-8"}
                    })
                    .then(
                        function(response) {
                            response.json().then(function(data) {
                            console.log(response)
                            if (response.status == 200) {
                                $('#sp_tmp_' + index).text("成功")
                            }
                            else {
                                $('#sp_tmp_' + index).text("失败")
                            }
                        });
                    })
                })
                $('#sp_info_body').append('<br /><span><strong>删除完成！</strong></span>')
            } else {
                $('#sp_info_title').text('错误')
                $('#sp_info_body').append('<span>您似乎木有选择 <strong>要删除</strong> 的标签</span>')
                $('#mdl_info').modal('show')
            }
        }

     </script>
</body>

</html>